package nayasis.common.db.manager.sql;

import java.util.Map;

import nayasis.common.model.NData;
import nayasis.common.model.NMultiData;
import nayasis.common.model.NVo;

import org.jdom2.Content;
import org.jdom2.Element;

public class SqlMap extends NVo {

    private static final int KEY_TYPE      = 0;
    private static final int KEY_CONDITION = 1;
    private static final int KEY_VAL       = 2;

    private static final int TYPE_TEXT      = 0;
    private static final int TYPE_IF        = 1;
    
	private NMultiData sql = new NMultiData();
	
	private String dbSpec;
	
	public String getSql() {
	    return this.sql.getString( "VAL", 0 );
	}
	
	public String getSql( Map<String, ParamValue> bindingParam ) {
	    
	    StringBuffer sb = new StringBuffer();
	    
	    for( NData e : sql ) {

	        if( e.getInteger(KEY_TYPE) == TYPE_IF && ! isTrue(e.getString(KEY_CONDITION), bindingParam) ) continue;
	        
	        sb.append( e.getString(KEY_VAL) );
	        
	    }
	    
	    return sb.toString();
	    
	}

	private boolean isTrue( String condition, Map<String, ParamValue> bindingParam ) {
	    return true;
	}
	
	public void setSql( String sql ) {
	    
	    this.sql.clear();

	    this.sql.add( KEY_TYPE, TYPE_TEXT );
	    this.sql.add( KEY_VAL,  sql  );
	    
	}

	
	public void setSql( Element sqlElement ) {
	    
	    this.sql.clear();

        for( Content content : sqlElement.getContent() ) {
            
            switch( content.getCType() ) {
                
                case Text : 

                    this.sql.add( KEY_TYPE, TYPE_TEXT               );
                    this.sql.add( KEY_VAL,  content.getValue() );
                    
                    break;

                case Element :

                    Element e = (Element) content;
                    
                    if( ! "if".equalsIgnoreCase(e.getName()) ) continue;
                    
                    this.sql.add( KEY_TYPE,      TYPE_IF                                );
                    this.sql.add( KEY_CONDITION, e.getAttributeValue("condition" ) );
                    this.sql.add( KEY_VAL,       content.getValue()                );
                    
                    break;
                    
                default :
                    break;
            }
            
        }
	    
	}
	
	public String getDbSpec() {
	    return this.dbSpec;
	}
	
	public void setDbSpec( String dbSpec ) {
	    this.dbSpec = dbSpec;
	}

	public String toString() {
	    return sql.toString();
	}
	
}
